package repository

import (
	"context"

	"gitee.com/zhyclouds/fable-scribe/internal/domain"
	"gitee.com/zhyclouds/fable-scribe/internal/repository/dao"
)

var (
	ErrRecordNotFound    = dao.ErrRecordNotFound
	ErrDuplicateUsername = dao.ErrDuplicateUsername
)

// UserRepository 用户仓库接口
type UserRepository interface {
	Create(ctx context.Context, user domain.User) error
	FindByUsername(ctx context.Context, username string) (domain.User, error)
}

// GORMUserRepository 用户仓库实现，实现 UserRepository 接口
type GORMUserRepository struct {
	userDAO dao.UserDAO
}

// NewGORMUserRepository 创建用户仓库实例，返回 UserRepository 接口类型
func NewGORMUserRepository(userDAO dao.UserDAO) UserRepository {
	return &GORMUserRepository{
		userDAO: userDAO,
	}
}

// Create 创建用户
func (r *GORMUserRepository) Create(ctx context.Context, user domain.User) error {
	// 转换领域模型到DAO模型
	userDAO := dao.User{
		Username: user.Username,
		Nickname: user.Nickname,
		Password: user.Password,
	}

	return r.userDAO.Create(ctx, userDAO)
}

// FindByUsername 根据用户名查找用户
func (r *GORMUserRepository) FindByUsername(ctx context.Context, username string) (domain.User, error) {
	userDAO, err := r.userDAO.FindByUsername(ctx, username)
	if err != nil {
		return domain.User{}, err
	}

	// 转换DAO模型到领域模型
	user := domain.User{
		ID:       userDAO.ID,
		Username: userDAO.Username,
		Nickname: userDAO.Nickname,
		Password: userDAO.Password,
		CTime:    userDAO.CTime,
		UTime:    userDAO.UTime,
	}

	return user, nil
}
